// pages/photoList/photoList.js

const qiniuUploader = require("../common/QNTool/qiniuUploader.js");

// 初始化七牛相关参数
function initQiniu() {
  var options = {
    region: 'ECN',
    uptoken: this.data.qntoken,
    domain: 'http://ohc2uub90.bkt.clouddn.com',
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 所有的 相册和内容
    photoList: [],
    //每个相册 的对象
    photoUrlList: [],
    // 专辑相册
    menuList: [],
    //将要通过七牛上传的 url
    imageURL: "",
    qntoken: "",
    // 专辑栏目 scroll的偏移量
    scrollOffset: 100,
    isSelect: false,
    selectIndex: 999,
    // 新建专辑 弹框是否 显示
    hiddenmodalput: true,
    // 输入的 新的专辑 名称
    voteTitle: '',
    // 用户权限
    permissions: "0"

  },
  // 下拉列表 点击事件
  customButtonClick: function(res) {
    wx.arrayBufferToBase64(arraybuffer)
    console.log(res)
    if (res.detail.index == 0) {
      // 上传
      this.uploadClicks()
    } else if (res.detail.index == 1) {
      // 新建相册
      this.setData({
        hiddenmodalput: !this.data.hiddenmodalput
      })
    } else {
      //  注销账号
      this.logOutUser()
    }
  },

  logOutUser: function() {
    wx.clearStorage()
    wx.redirectTo({
      url: "../Log/log",
    })
  },
  modalConfirm: function(e) {
    var title = this.data.voteTitle
    if (this.data.voteTitle.length > 5) {
      title = this.data.voteTitle.slice(0, 5)
      wx.showToast({
        title: '最大支持5个字',
      })
    }
    var albumNumber = this.data.menuList.length

    var that = this;
    // 获取 token
    try {
      var value = wx.getStorageSync('userLoginToken')
      if (value) {
        wx.request({
          // url: 'http://localhost:8181/upLoad/albumData',
          url: 'https://zhj1214.club/upLoad/albumData',
          method: 'post',
          data: {
            token: value,
            name: title,
            albumId: albumNumber
          },
          success: function(res) {
            console.log(res)
            console.log('创建 成功： ' + res.data.data)
            that.setData({
              menuList: res.data.data,
              hiddenmodalput: true
            });
          },
          fail: function(res) {
            console.log('失败')
            wx.showToast({
              title: '创建失败',
            })
          }
        })
      }
    } catch (e) {
      console.log('获取本地 token 缓存失败 ')
      wx.showToast({
        title: 'toek失效，重新登录再试',
      })
    }
  },
  modalCancel: function(e) {
    this.setData({
      hiddenmodalput: true
    });
  },
  voteTitle: function(e) {
    console.log(e.detail.value)
    this.data.voteTitle = e.detail.value;
  },

  /**
   * 滚动菜单 事件
   */
  upper: function(e) {
    console.log('upper' + e)
  },
  lower: function(e) {
    console.log('lower' + e)
  },
  scroll: function(e) {
    // console.log('scroll' + e)
  },

  itemClick: function(e) {
    console.log(e)
    var width = wx.getSystemInfoSync().windowWidth * 0.15
    var legth = e.currentTarget.dataset.index * width + width / 2
    legth = legth - wx.getSystemInfoSync().windowWidth / 2

    // 默认根据选择的 专辑id 返回指定专辑内容
    var List = []
    if (this.data.photoList.length > e.currentTarget.dataset.index) {
      List = this.data.photoList[e.currentTarget.dataset.index]
    }

    this.setData({
      isSelect: true,
      selectIndex: e.currentTarget.dataset.index,
      scrollOffset: legth,
      photoUrlList: List
    })
    console.log('selectIndex  ' + this.data.selectIndex + "  " + '  ' + width + '  ' + legth)
  },

  // 获取 七牛上传凭证
  getServiceQNtoken: function(res) {
    var that = this;
    wx.request({
      url: 'https://zhj1214.club/query/qntoken',
      success: function(res) {
        console.log('七牛token  ' + res.data.token);
        that.setData({
          qntoken: res.data.token,
        });
      },
      fail: function(error) {
        console.log(error)
        wx.showToast({
          title: '服务异常',
        })
      }
    })
  },
  // 拿到凭证 之后开始上传
  uploadClicks: function(res) {
    var that = this;
    if (!that.data.qntoken) {
      Console.log(that.data.qntoken)
      wx.showToast({
        title: 'token失效',
      })
      return;
    }
    wx.chooseImage({
      success: function(res) {
        var tempFilePaths = res.tempFilePaths[0]
        var path = tempFilePaths.slice(7)
        console.log('上传路径' + tempFilePaths)
        console.log(res.tempFilePaths)
        wx.showLoading({
          title: '上传中...',
        })
        // 交给七牛上传
        qiniuUploader.upload(tempFilePaths, (res) => {
            console.log(res.imageURL)
            if (res.imageURL) {
              wx.showToast({
                icon: 'success'
              })
              that.setData({
                'imageObject': res,
              });
              that.uploadImgURLdatatoService(res)
            } else {
              wx.showToast({
                title: '上传失败',
              })
            }
          }, (error) => {
            wx.showToast({
              title: '上传失败',
            })
            console.error('error: ' + JSON.stringify(error));
          }, {
            region: 'ECN', // 华北区
            uptoken: that.data.qntoken,
            domain: 'http://ohc2uub90.bkt.clouddn.com',
            shouldUseQiniuFileName: false
          },
          (progress) => {
            console.log('上传进度', progress.progress)
            console.log('已经上传的数据长度', progress.totalBytesSent)
            console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
          }
        );
      },
    })
  },
  // 上传 url 到服务器
  uploadImgURLdatatoService: function(response) {
    var that = this;
    let imageurl = response.imageURL;
    console.log('开始上传 url')
    console.log('selectIndex  ' + that.data.selectIndex)
    console.log(imageurl)
    if (that.data.selectIndex == 999) {
      that.data.selectIndex = 0
    }
    wx.getStorage({
      key: 'userLoginToken',
      success: function(res) {
        wx.request({
          url: 'https://zhj1214.club/upLoad/photoData',
          // url: 'http://0.0.0.0:8181/upLoad/photoData',
          method: 'post',
          data: {
            token: res.data,
            imgname: "zhjzhjzhjtest",
            url: imageurl,
            category: "photoAlbum",
            albumId: that.data.selectIndex
          },
          success: function(data) {
            console.log('上传成功：' + data.data.data.imagUrl)
            var imgObj = {
              albumId: that.data.selectIndex,
              name: "zhjzhjzhjtest",
              url: data.data.data.imagUrl,
              category: "photoAlbum",
              userid: 666
            }
            that.data.photoUrlList.push(imgObj)
            that.setData({
              photoUrlList: that.data.photoUrlList
            })
          },
          fail: function(res) {
            console.log('失败')
            wx.showToast({
              title: '上传失败',
            })
          }
        })
      }
    })
  },

  // copy 图片地址
  copyClick: function(res) {
    var urltemp = this.data.photoUrlList[res.currentTarget.dataset.index];
    console.log(urltemp.url)
    // http://ohc2uub90.bkt.clouddn.com  https://qclud.zhj1214.club
    let url = urltemp.url.replace('http://ohc2uub90.bkt.clouddn.com', 'https://qclud.zhj1214.club')
    console.log(url + '再看看')
    // 拿到URL 以后要上传服务器然后进行下载凭证的加密 再返回一个新的url
    wx.request({
      url: 'https://zhj1214.club/query/qnimgurl',
      method: 'post',
      data: {
        fileName: url
      },
      success: function(res) {
        console.log(res)
        wx.setClipboardData({
          data: url,
          success: function() {
            wx.showToast({
              title: 'URL已复制',
            })
          }
        })
      },
      fail: function(error) {
        wx.showToast({
          title: '服务异常',
        })
      }
    })
  },

  // 下载图片到本地
  downLoadClick: function(res) {
    // 保存之前先download一下, 把返回的tempFilePath临时文件路径给wx.saveImageToPhotosAlbum的filePath参数
    let urltemp = this.data.photoUrlList[res.currentTarget.dataset.index];
    console.log(urltemp.url)
    // http://ohc2uub90.bkt.clouddn.com  https://qclud.zhj1214.club
    let url = urltemp.url.replace('http://ohc2uub90.bkt.clouddn.com', 'https://qclud.zhj1214.club')
    console.log(url + '再看看')

    wx.getImageInfo({
      src: url,
      success: function(ret) {
        var path = ret.path;
        wx.showLoading({
          title: '保存ing...',
        })
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success(result) {
            console.log(result)
            wx.showToast({
              icon: 'success'
            })
          },
          fail: function(error) {
            console.log(error)
            wx.showToast({
              title: '保存失败',
            })
          }
        })
      },
      fail: function(error) {
        console.log(error)
        wx.showToast({
          title: '网络异常',
        })
      }
    })
  },

  // 删除 图片
  deleteClick: function(res) {
    var that = this
    let url = that.data.photoUrlList[res.currentTarget.dataset.index];
    console.log(url.url)
    wx.showLoading({
      title: '请稍等',
    })
    wx.request({
      url: 'https://zhj1214.club/query/deletephoto',
      // url: 'http://0.0.0.0:8181/query/deletephoto',
      data: {
        imgurl: url.url
      },
      method: 'post',
      success: function(result) {
        if (result.data.token == "success") {
          wx.showToast({
            icon: 'success'
          })
          var array = that.data.photoUrlList
          array.splice(res.currentTarget.dataset.index, 1)
          that.setData({
            photoUrlList: array
          })
        } else {
          wx.showToast({
            icon: '删除失败'
          })
        }
      },
      fail: function(error) {
        wx.showToast({
          title: '服务异常' + error.info,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.getServiceQNtoken();
    var that = this;
    // 获取 token
    try {
      var value = wx.getStorageSync('userLoginToken')
      var Authorization = "0"

      if (value) {
        wx.request({
          url: 'https://zhj1214.club/query/Photolist',
          // url: 'http://0.0.0.0:8181/query/Photolist',
          method: 'post',
          data: {
            token: value,
          },
          success: function(res) {
            console.log('获取成功')
            console.log(res)
            that.data.menuList = res.data.albumList
            // 默认根据选择的 专辑id 返回指定专辑内容
            that.data.photoUrlList = res.data.photoList[0]
            Authorization = res.data.permissions
            // 是否展示 隐藏入口
            var imgObj = {
              albumId: "0",
              name: "showShoes",
              url: "https://qclud.zhj1214.club/GXPhotos.png",
              userid: 9990
            }
            if (Authorization == "110" || Authorization == "111") {
              imgObj.url = "https://qclud.zhj1214.club/wsc.jpg";
              if (Authorization == "111") {
                var superObj = {
                  albumId: "0",
                  name: "superObj",
                  url: "https://qclud.zhj1214.club/addGood.jpg",
                  userid: 9991
                }
                that.data.photoUrlList.push(superObj)
              }
            }
            that.data.photoUrlList.push(imgObj)
            // 颠倒 数组中的顺序
            that.data.photoUrlList.reverse();
            that.setData({
              photoList: res.data.photoList,
              photoUrlList: that.data.photoUrlList,
              menuList: that.data.menuList,
              permissions: Authorization
            })
          }
        })
      }
    } catch (e) {
      console.log('获取本地 token 缓存失败 ')
      wx.showToast({
        title: 'toek失效，重新登录再试',
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    console.log("刷新");
    wx.showNavigationBarLoading() // 在当前页面显示导航条加载动画
    wx.stopPullDownRefresh()

    // var random = Math.floor(Math.random() * this.data.photoUrlList.length)
    // console.log('随机数是'+random)
    // var imgUrl = this.data.photoUrlList[random]
    // this.data.photoUrlList.push(imgUrl)
    // this.setData({
    //   photoUrlList: this.data.photoUrlList
    // })
    wx.hideNavigationBarLoading()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

/**
   * 用户 预览图片
   */
  previewImageClick: function(res) {
    var that = this
    let urlObj = that.data.photoUrlList[res.currentTarget.dataset.index];

    if (urlObj.userid == 9990) {
      wx.navigateTo({
        url: '../shoesPage/shoesPage?permissions=' + that.data.permissions,
      })
      return;
    } else if (urlObj.userid == 9991) {
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function(res) {
          wx.navigateTo({
            url: '../releaseGoodsPage/releaseGoodsPage?photoList=' + JSON.stringify(res.tempFilePaths),
          })
        },
        fail: function(res) {
          console.log('失败')
          console.log(res)
        }
      })
      return;
    }
    var urls = []
    for (var i = 0; i < that.data.photoUrlList.length; i++) {
      let img = that.data.photoUrlList[i]
      urls.push(img.url)
    }

    wx.previewImage({
      urls: urls,
      current: urlObj.url,
      success: function() {
        // console.log("图片预览 成功")
      },
      fail: function() {
        console.log("图片预览 失败")
      }
    })
  }
  //   ms.sm 图片上传 流程
  // uploadClick: function (res) {
  //   var that = this;
  //   wx.chooseImage({
  //     success: function (res) {
  //       var tempFilePaths = res.tempFilePaths[0]
  //       var path = tempFilePaths.slice(7)
  //       console.log('上传路径' + tempFilePaths)
  //       console.log(res.tempFilePaths)
  //       wx.uploadFile({
  //         url: 'https://sm.ms/api/upload',
  //         filePath: tempFilePaths,
  //         name: 'smfile',
  //         success: function (res) {
  //           var jsonStr = res.data;
  //           jsonStr = jsonStr.replace(" ", "");
  //           if (typeof jsonStr != 'object') {
  //             jsonStr = jsonStr.replace(/\ufeff/g, ""); //重点
  //             var jj = JSON.parse(jsonStr);
  //             res.data = jj;
  //           }
  //           let imageurl = res.data.data.url;
  //           wx.getStorage({
  //             key: 'userLoginToken',
  //             success: function (res) {
  //               wx.request({
  //                 url: 'http://localhost:8181/upLoad/photoData',
  //                 method: 'post',
  //                 data: {
  //                   token: res.data,
  //                   imgname: "zzzzzzz",
  //                   url: imageurl
  //                 },
  //                 success: function (data) {
  //                   console.log('成功')
  //                   that.data.photoUrlList.push(imageurl)
  //                   that.setData({
  //                     photoUrlList: that.data.photoUrlList
  //                   })
  //                 },
  //                 fail: function (res) {
  //                   console.log('失败')
  //                 }
  //               })
  //             }
  //           })
  //         }
  //       })
  //     },
  //   })
  // }
})